﻿using CoreLims.Models;
using CoreLims.Models.CoreLims;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoreLims.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly CoreLimsContext dbContext;
        private UserManager<IdentityUser> _UserManager;
        private RoleManager<IdentityRole> _RoleManager;

        public HomeController(ILogger<HomeController> logger, CoreLimsContext context, UserManager<IdentityUser> usrManager, RoleManager<IdentityRole> roleManager)
        {
            _logger = logger;
            dbContext = context;
            _UserManager = usrManager;
            _RoleManager = roleManager;
        }

        public IActionResult Login()
        {
            return View();
        }

        public IActionResult Index()
        {            
            ViewData["Title"] = "EasyLims";
            return View();
        }

        public IActionResult Register()
        {
            return View();
        }

        public IActionResult Forbidden()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpPost]
        public string GetLoginUser()
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            if (user != null)
                return user.FullName + "：" + DateTime.Now.ToString("yyyy年MM月dd, dddd");
            else
                return "获取登录用户失败！";
        }

        [HttpPost]
        public async Task<string> GetUserRolesSt() // 获得用户所属角色名字符串
        {
            var users = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var user = await _UserManager.FindByNameAsync(users.IdentityName);
            var userRoles = await _UserManager.GetRolesAsync(user);

            StringBuilder sb = new StringBuilder();
            foreach (var role in userRoles)
            {
                sb.Append(role.ToString() + ",");
            }

            return sb.ToString();
        }

    }
}
